{% extends "base.html" %}
{% comment 'header' %}
# This file is part of opentaps Smart Energy Applications Suite (SEAS).

# opentaps Smart Energy Applications Suite (SEAS) is free software:
# you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# opentaps Smart Energy Applications Suite (SEAS) is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.

# You should have received a copy of the GNU Lesser General Public License
# along with opentaps Smart Energy Applications Suite (SEAS).
# If not, see <https://www.gnu.org/licenses/>.
{% endcomment %}

{% load static %}

{% block title %}
{% if meter_id %}
  Import Data from UtilityAPI Meter
{% else %}
  Add Meter from UtilityAPI
{% endif %}
{% endblock %}

{% block content %}
<div class="container">

  {% include "core/_breadcrumbs.html" %}

  <div class="card mb-3" id="meterdataimport" v-cloak>
    <div class="card-body">
      {% if meter_id %}
        <h2>Import Data from UtilityAPI Meter</h2>
      {% else %}
        <div class="row m-0">
            <h2>Add Meter from UtilityAPI</h2>
            <div class="text-right flex-grow-1">
              <a class="btn btn-primary" href="{% url 'core:meter_create' site_id %}"><i class="fa fa-plus"></i> Add Meter</a>
            </div>
        </div>
      {% endif %}
      <br/>
      {% block inner_content %}

      <div class="alert alert-danger mt-3" role="alert" v-if="errors.error">
          ${ errors.error }
      </div>
      <div class="alert alert-success mt-3" role="alert" v-if="successes.success" v-cloak>
        ${ successes.success }
      </div>

      {% if meter_uid %}
      <div>
        <div>Last meter reading: {{ last_timestamp }}</div>
        <div>UtilityAPI meter uid: {{ meter_uid }}</div>
        <b-button variant="primary" v-on:click.stop.prevent="import_utilityapi_meter_data()" :disabled="isImportDisabled">
          <i class="fa fa-plus"></i> Import Data
        </b-button>
        <b-spinner v-if="isImportDisabled" variant="secondary"></b-spinner>
      </div>
      {% else %}
      <div class="form-group">
        <label for="customerEmail">Customer Email*</label>
        <b-form-input type="email" id="customerEmail" placeholder="Input Email" :state="customerEmailState" v-model="customerEmail" required></b-form-input>
        <b-form-invalid-feedback id="customerEmail">
            Customer Email is required
        </b-form-invalid-feedback>
      </div>

      <div class="text-right flex-grow-1">
        <b-button v-if="!isSearchDisabled && showAuthButton" variant="primary" v-on:click.stop.prevent="ask_authorization()" :disabled="isSearchDisabled">
          Create Authorization Form
        </b-button>

        <b-button v-if="!isSearchDisabled" variant="primary" v-on:click.stop.prevent="get_utilityapi_meters()" :disabled="isSearchDisabled">
          <i class="fa fa-search"></i> Search Meters
        </b-button>
        <b-spinner v-if="isSearchDisabled" variant="secondary"></b-spinner>
      </div>

      <div v-if="authUrl" class="alert alert-success mt-3" role="alert">
        <p>UtilityAPI authorization form successfully created. Please send this <a :href="authUrl" target="_blank">link</a> to your customer to confirm authorization.</p>
        <div>${ authUrl }</div>
      </div>

      <div class="mt-3" v-if="meters.length">
          {% if meter_id %}
          <label for="utilityapiMeter">UtilityAPI Meters</label>
          <select name="utilityapiMeter" class="select form-control" id="id_utilityapiMeter" v-model="selectedMeter">
            <option v-for="c in meters" :value="c.uid">${ c.description }</option>
          </select>
          <div class="mt-3 text-right">
            <b-button variant="primary" v-on:click.stop.prevent="import_utilityapi_meter_data()" :disabled="isImportDisabled">
              <i class="fa fa-plus"></i> Import Data
            </b-button>
            <b-spinner v-if="isImportDisabled" variant="secondary"></b-spinner>
          </div>
          {% else %}
          <b-form-group label="UtilityAPI Meters">
              <b-form-checkbox-group
                id="id_utilityapiMeters"
                v-model="selectedMeters"
                :options="meters"
                name="utilityapiMeters"
                value-field="uid"
                text-field="description"
                stacked
               ></b-form-checkbox-group>
          </b-form-group>
          <div class="mt-3" v-if="weatherStations.length">
              <label for="weatherStation">Weather Station</label>
              <select name="weatherStation" class="select form-control" id="id_weatherStation" v-model="selectedWeatherStation">
                <option v-for="c in weatherStations" :value="c.id">${ c.value }</option>
              </select>
          </div>
          <div class="mt-3 text-right">
            <b-button variant="primary" v-on:click.stop.prevent="import_utilityapi_meters()" :disabled="isImportDisabled">
              <i class="fa fa-plus"></i> Add Meters
            </b-button>
            <b-spinner v-if="isImportDisabled" variant="secondary"></b-spinner>
          </div>
          {% endif %}
      </div>
      {% endif %}

      {% endblock inner_content %}
    </div>
  </div>
</div>

<script>
(function() {
  {% load js_csrf_token from core_tags %}
  const CSRF_TOKEN = '{% js_csrf_token %}';

  new Vue({
    delimiters: ['${', '}'],
    name: 'meterdataimport',
    el: '#meterdataimport',
    data() {
      return {
        csrfmiddlewaretoken: CSRF_TOKEN,
        customerEmailState: null,
        customerEmail: null,
        authUrl: null,
        isSearchDisabled: false,
        isImportDisabled: false,
        showAuthButton: false,
        weatherStations: [],
        selectedWeatherStation: {%if weather_station_id %}'{{ weather_station_id|safe}}'{%else%}null{%endif%},
        meters: [],
        selectedMeters: [],
        selectedMeter: {%if meter_uid %}'{{ meter_uid|safe}}'{%else%}null{%endif%},
        errors: {'error': null},
        successes:  {'success': null},
        meterId: {%if meter_id %}'{{ meter_id|safe}}'{%else%}null{%endif%},
        siteId: {%if site_id %}'{{ site_id|safe}}'{%else%}null{%endif%},
      }
    },

    mounted() {
      console.log('mounted..');
    },
    methods: {
      get_utilityapi_meters() {
          console.log('get_utilityapi_meters..');
          this.customerEmailState = null;
          this.authUrl = null;
          this.errors = {'error': null};
          this.meters = [];
          if (!this.customerEmail) {
              this.customerEmailState = false;
          } else {
              this.isSearchDisabled = true;
              this.showAuthButton = false;
              url = dutils.urls.resolve('utilityapi_meters_json') + '?customer_email=' + this.customerEmail;
              axios.get(url)
                .then(x => {
                  console.log('get_utilityapi_meters', x.data)
                  if (x.data.error) {
                      this.errors['error'] = x.data.error;
                      if (x.data.error_code && x.data.error_code == 1) {
                          this.showAuthButton = true;
                      }
                  } else if (!x.data.meters || (x.data.meters && x.data.meters.length == 0)) {
                      this.errors['error'] = 'Cannot find customer UtilityAPI meters.';
                  } else {
                      this.meters = x.data.meters;
                      if (this.meterId) {
                          this.selectedMeter = this.meters[0].uid;
                      } else {
                          this.selectedMeters = [];
                          for (var i=0; i<x.data.meters.length; i++) {
                              this.selectedMeters.push(x.data.meters[i].uid);
                          }
                      }
                      this.get_weather_stations();
                  }
                  this.isSearchDisabled = false;
                })
                .catch(err => {
                  console.error('loading utility rates error :', err);
                  e = getResponseError(err);
                  this.errors = e;
                  this.isSearchDisabled = false;
                });
          }
      },
      import_utilityapi_meter_data() {
          this.errors = {'error': null};
          this.successes = {'success': null};
          url = dutils.urls.resolve('utilityapi_meter_data_import', { meter_id: this.meterId });
          console.log('import_utilityapi_meter_data: this.selectedMeter', this.selectedMeter)
          console.log('url =', url)
          if (!this.selectedMeter) {
              this.errors = {'error': 'Please, select UtilityAPI Meter.'};
          } else {
              this.isImportDisabled = true;
              data = {meter_uid: this.selectedMeter};
              axios.post(url, data, {headers: {'X-CSRFToken': this.csrfmiddlewaretoken}})
                .then(x => x.data)
                .then(x => {
                    if (x.error) {
                        this.errors['error'] = x.error;
                    } else if (x.success) {
                        console.log('import_utilityapi_meter_data, result = ', x);
                        if (x.message) {
                            this.successes = {'success': x.message};
                        } else {
                            this.successes = {'success': 'Successfully imported UtilityAPI Meter Readings'};
                        }
                    }
                    this.isImportDisabled = false;
                })
                .catch(err => {
                  e = getResponseError(err);
                  console.error(e, err);
                  this.errors = e;
                  this.isImportDisabled = false;
                });
          }
      },
      import_utilityapi_meters() {
          this.errors = {'error': null};
          this.successes = {'success': null};
          url = dutils.urls.resolve('utilityapi_meters_data_import', { site_id: this.siteId });
          console.log('import_utilityapi_meters: this.selectedMeters', this.selectedMeters)
          console.log('url =', url)
          if (!this.selectedMeters || !this.selectedMeters.length) {
              this.errors = {'error': 'Please, select UtilityAPI Meters.'};
          } else {
              this.isImportDisabled = true;
              data = {meter_uids: this.selectedMeters, weather_station_id: this.selectedWeatherStation};
              axios.post(url, data, {headers: {'X-CSRFToken': this.csrfmiddlewaretoken}})
                .then(x => x.data)
                .then(x => {
                    if (x.error) {
                        this.errors['error'] = x.error;
                    } else if (x.success) {
                        console.log('import_utilityapi_meters, result = ', x);
                        if (x.message) {
                            this.successes = {'success': x.message};
                        } else {
                            this.successes = {'success': 'Successfully imported UtilityAPI Meters and Readings'};
                        }
                    }
                    this.isImportDisabled = false;
                })
                .catch(err => {
                  e = getResponseError(err);
                  console.error(e, err);
                  this.errors = e;
                  this.isImportDisabled = false;
                });
          }
      },
      ask_authorization() {
          console.log('ask_authorization..');
          this.customerEmailState = null;
          this.authUrl = null;
          this.errors = {'error': null};
          if (!this.customerEmail) {
              this.customerEmailState = false;
          } else {
              this.isSearchDisabled = true;
              this.showAuthButton = false;
              url = dutils.urls.resolve('utilityapi_create_form');
              data = {customer_email: this.customerEmail};
              axios.post(url, data, {headers: {'X-CSRFToken': this.csrfmiddlewaretoken}})
                .then(x => x.data)
                .then(x => {
                    if (x.error) {
                        this.errors['error'] = x.error;
                        this.showAuthButton = true;
                    } else if (x.success) {
                        console.log('ask_authorization, result = ', x);
                        if (x.auth_form) {
                            this.authUrl = x.auth_form.url;
                        } else {
                            this.errors['error'] = 'Cannot create UtilityAPI authorization form';
                            this.showAuthButton = true;
                        }
                    }
                    this.isSearchDisabled = false;
                })
                .catch(err => {
                  e = getResponseError(err);
                  console.error(e, err);
                  this.errors = e;
                  this.isSearchDisabled = false;
                });
          }
      },
      get_weather_stations() {
          console.log('get_weather_stations..');
          this.errors = {'error': null};
          this.weatherStations = [];
          url = dutils.urls.resolve('weather_stations_json');
          axios.get(url)
            .then(x => {
              console.log('get_weather_stations', x.data.items)
              if (x.data.error) {
                  this.errors['error'] = x.data.error;
              } else if (!x.data.items || (x.data.items && x.data.items == 0)) {
                  this.errors['error'] = 'Cannot get weather stations list.';
              } else {
                  this.weatherStations = x.data.items;
              }
            })
            .catch(err => {
              console.error('get_weather_stations error :', err);
              e = getResponseError(err);
              this.errors = e;
            });
      }
    }
  });
})();
</script>

{% endblock content %}
